package org.android.brasil.projetos.oktoberfest2011.view;

import java.io.File;

import org.android.brasil.projetos.oktoberfest2011.R;
import org.android.brasil.projetos.oktoberfest2011.view.controller.HTTPThread;
import org.android.brasil.projetos.oktoberfest2011.view.controller.HTTPThreadStack;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.ImageView;

public class TwitterImageView extends ImageView {
	
	private String username;
	private String local;
	private String remote;
	private HTTPThread thread = null;

	public TwitterImageView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public TwitterImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public void setLocalURI(String local) {
		this.local = local;
	}

	public void setRemoteURI(String uri) {
		if (uri.startsWith("http")) {
			this.remote = uri;
		}
	}
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void loadImage() {
		if (this.remote != null) {
			if (this.local == null) {
				this.local = Environment.getExternalStorageDirectory() + "/.remote-image-view-cache/" + this.username + ".jpg";
			}
			// check for the local file here instead of in the thread because
			// otherwise previously-cached files wouldn't be loaded until after
			// the remote ones have been downloaded.
			File fLocal = new File(this.local);
			if (fLocal.exists()) {
				this.setFromLocal();
			} else {
				// we already have the local reference, so just make the parent
				// directories here instead of in the thread.
				fLocal.getParentFile().mkdirs();
				this.queue();
			}
		}
	}

	@Override
	public void finalize() {
		if (this.thread != null) {
			HTTPThreadStack queue = HTTPThreadStack.getInstance();
			queue.dequeue(this.thread);
		}
	}

	private void queue() {
		if (this.thread == null) {
			this.thread = new HTTPThread(this.remote, this.local, handler);
			HTTPThreadStack stack = HTTPThreadStack.getInstance();
			stack.enqueue(this.thread, HTTPThreadStack.PRIORITY_HIGH);
		}
		setImageResource(R.drawable.ic_launcher);
	}

	private void setFromLocal() {
		this.thread = null;
		Drawable d = Drawable.createFromPath(this.local);
		if (d != null) {
			this.setImageDrawable(d);
		}
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			TwitterImageView.this.setFromLocal();
		}
	};
}
